iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0

前言

到目前為止,我們已經學會了變數、資料型別、運算子、條件判斷與迴圈,能寫出小型的程式。但如果要處理更複雜的需求,例如隨機數、日期時間、數學計算,甚至是網路請求,就不必自己從零開始。Python 已經幫我們準備了許多 模組(Module),就像一個工具箱,隨時可以拿來使用。

在程式設計的世界裡:

  • 模組:好比一個單獨的工具包,提供特定的功能(例如計算平方根)。
  • 套件:像是一個完整的工具櫃,裡面有多個工具包。
  • 函式庫:則是一整間工具室,收集了多個工具櫃,針對某個領域(如資料分析、人工智慧)提供完整功能。

透過 import,我們可以直接把這些工具搬進程式裡使用,大幅減少重複造輪子的時間。除了 Python 內建的標準模組,還能安裝社群開發的第三方模組,甚至自己寫模組來重複利用。

今天的目標是:

  1. 了解模組、套件與函式庫的差別。
  2. 學會使用 import 的各種方式。
  3. 認識常見的標準模組(mathrandomdatetimeos)。
  4. 嘗試撰寫並使用自己的模組。
  5. 學會安裝與使用第三方模組(pip install)。

換句話說,今天會讓我們學會「善用別人寫好的工具」,讓程式不只會重複運算,還能真正變得強大又方便。

1. 什麼是模組?

基本概念

  • 模組(Module):一個 Python 檔案(.py),裡面定義了變數、函式、類別,可以被其他程式載入使用。
  • 套件(Package):包含多個模組的資料夾。
  • 函式庫(Library):一組相關套件的集合,提供特定領域的功能。

模組分類

類型 說明 範例 取得方式
標準模組 Python 官方內建 math, random, datetime 直接使用
第三方模組 社群開發,需安裝 requests, numpy, openai pip install
自訂模組 自己撰寫的檔案 tools.py, config.py 同專案資料夾

2. import 基本語法

2-1 基本載入

import math
print(math.sqrt(25))  # 開根號 ➜ 5.0
print(math.pi)        # 圓周率 ➜ 3.14159...

2-2 使用別名(as)

import math as m
print(m.sqrt(16))     # 4.0
print(m.ceil(3.14))   # 4 (無條件進位)

好處:縮短命名、方便閱讀,尤其對於長模組名很有用。

2-3 載入特定函式(from...import)

from math import sqrt, pi, ceil
print(sqrt(16))    # 4.0 (不用寫 math.sqrt)
print(pi)          # 3.141592653589793
print(ceil(3.14))  # 4

優點:不用加 模組名稱. 前綴
風險:容易與自己變數重名,需小心命名衝突

2-4 載入所有內容(不建議)

from math import *
print(sin(pi / 2))  # 1.0

為什麼不建議?

  • 容易產生命名衝突
  • 難以追蹤函式來源
  • 影響程式碼可讀性

3. 常見標準模組介紹

3-1 math(數學運算)

import math

# 基本運算
print(math.sqrt(25))        # 開根號 ➜ 5.0
print(math.pow(2, 3))       # 2的3次方 ➜ 8.0
print(math.ceil(3.14))      # 無條件進位 ➜ 4
print(math.floor(3.99))     # 無條件捨去 ➜ 3

# 常數
print(math.pi)              # 圓周率
print(math.e)               # 自然對數底

3-2 random(隨機數生成)

import random

# 隨機整數和浮點數
print(random.randint(1, 10))     # 1-10 的隨機整數
print(random.random())           # 0-1 的隨機浮點數

# 隨機選擇
colors = ['red', 'blue', 'green']
print(random.choice(colors))     # 隨機選一個顏色

# 打亂清單
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)  # 被打亂的清單

3-3 datetime(日期時間)

from datetime import datetime, date

# 取得現在時間
now = datetime.now()
print(f"現在時間: {now}")
print(f"格式化: {now.strftime('%Y-%m-%d %H:%M:%S')}")

# 只處理日期
today = date.today()
print(f"今天: {today}")
print(f"年份: {today.year}")

3-4 os(作業系統介面)

import os

# 檔案和目錄操作
print(f"目前工作目錄: {os.getcwd()}")
print(f"目錄內容: {os.listdir('.')}")

# 檢查檔案是否存在
print(f"檔案是否存在: {os.path.exists('test.txt')}")

4. 自訂模組

建立自己的模組

假設你有一個檔案叫 tools.py

# tools.py
def greet(name):
    return f"Hello, {name}!"

def add(x, y):
    return x + y

# 模組常數
VERSION = "1.0"

使用自訂模組

# main.py
import tools

# 使用模組函式
print(tools.greet("Alice"))  # Hello, Alice!
print(tools.add(3, 5))       # 8
print(f"版本: {tools.VERSION}")

或者:

from tools import greet, add
print(greet("Bob"))    # Hello, Bob!
print(add(10, 20))     # 30

5. pip 安裝第三方模組

安裝套件

# 基本安裝
pip install requests

# 安裝特定版本
pip install requests==2.28.0

# 升級套件
pip install --upgrade requests

使用 requests 模組

import requests

# 發送 HTTP 請求
response = requests.get("https://httpbin.org/get")
print(f"狀態碼: {response.status_code}")
print(f"回應內容: {response.text}")

6. import 語法比較

寫法 使用方式 優點 缺點
import math math.sqrt(25) 清楚來源 需要前綴
import math as m m.sqrt(25) 簡短易讀 需記住別名
from math import sqrt sqrt(25) 直接使用 可能重名
from math import * sqrt(25) 最簡潔 不推薦

7. 常見錯誤與解決方案

錯誤對照表

錯誤類型 錯誤訊息 可能原因 解決方法
ModuleNotFoundError No module named 'xxx' 模組未安裝 使用 pip install xxx
ImportError cannot import name 'xxx' 函式名稱錯誤 檢查函式名稱拼字
AttributeError module has no attribute 'xxx' 屬性不存在 使用 dir() 檢查可用屬性

除錯小技巧

# 檢查模組有哪些功能
import math
print(dir(math))  # 列出所有可用功能

# 檢查模組是否已安裝
try:
    import requests
    print("requests 已安裝")
except ImportError:
    print("requests 未安裝")

8. 實戰練習

練習 1:圓面積計算器

import math

radius = float(input("請輸入圓的半徑: "))
area = math.pi * radius ** 2
print(f"圓面積是: {area:.2f}")

練習 2:隨機密碼生成器

import random
import string

def generate_password(length=8):
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))

password = generate_password(12)
print(f"隨機密碼: {password}")

練習 3:建立自己的工具模組

建立 mytools.py

# mytools.py
def celsius_to_fahrenheit(celsius):
    """攝氏轉華氏"""
    return celsius * 9/5 + 32

def is_even(number):
    """檢查是否為偶數"""
    return number % 2 == 0

使用:

import mytools

temp_f = mytools.celsius_to_fahrenheit(25)
print(f"25°C = {temp_f}°F")

print(f"4是偶數嗎? {mytools.is_even(4)}")

9. import 最佳實務

建議的 import 順序

# 1. 標準函式庫
import os
import sys
from datetime import datetime

# 2. 第三方套件  
import requests
import numpy as np

# 3. 自訂模組
from myproject import settings
import mytools

命名慣例

#  好的做法
import numpy as np              # 標準縮寫
import pandas as pd             # 標準縮寫  
import matplotlib.pyplot as plt # 標準縮寫

#  避免的做法
import numpy as n               # 不清楚的縮寫
from math import *              # 污染命名空間

10. 爲何要學習這個

即將接觸的進階概念

學會 import 後,你就準備好學習:

  1. 非同步程式設計import asyncio
  2. AI 工具整合import openaifrom langchain import ...
  3. 資料科學import pandas as pdimport numpy as np
  4. 網頁開發from flask import Flask

這些都建立在今天學的 import 基礎上!


上一篇
Day 3:條件判斷與流程控制(if / while / for)
系列文
一塊一塊拼湊的 AI 樂高世界之旅4
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言